package dang.action.order;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import dang.action.DangAction;
import dang.action.cart.Cart;
import dang.action.cart.CartItem;
import dang.common.Constant;
import dang.common.CookieUtil;
import dang.dao.DaoFactory;
import dang.dao.OrderDao;
import dang.entity.Order;
import dang.entity.User;
import dang.exception.DangException;

public class SaveOrderAction extends DangAction{
	public String execute() throws UnsupportedEncodingException, DangException {
		User user = (User) session.get("user");
		int userId= user.getId();
		List<CartItem> items=new ArrayList<CartItem>();
		Cart cart = (Cart) session.get("cart");
		if(cart!=null){
			items=cart.list();
		}else{
			cart=new Cart();
			String cartInfoId=(String) session.get("cartInfoId").toString();
			String cartInfo=CookieUtil.getCookie("cartInfo"+cartInfoId,request);
			items=cart.load(cartInfo);
		}
		double totalPrice=0;
		for (CartItem item : items) {
			totalPrice+=item.getQty()*item.getProduct().getDang_price()*(item.getProduct().isDeleted()?0:1);
		}
		OrderDao dao = DaoFactory.getOrderDao();
		Order order = new Order();
		order.setUser_id(userId);
		order.setTotal_price(totalPrice);
		order.setStatus(Constant.ORDER_NEW);
		int orderId=dao.saveOrder(order);
		dao.saveItems(items,orderId);
		return "success";
	}
}
